package initialize

import (
	"encoding/json"
	"fmt"
	"github.com/nacos-group/nacos-sdk-go/clients"
	"github.com/nacos-group/nacos-sdk-go/common/constant"
	"github.com/nacos-group/nacos-sdk-go/vo"
	"travel-app/common/config"
)

func Nacos() {

	nas := config.Config.Nacos
	clientConfig := constant.ClientConfig{
		NamespaceId:         nas.NameId, // 如果需要支持多namespace，我们可以场景多个client,它们有不同的NamespaceId。当namespace是public时，此处填空字符串。
		TimeoutMs:           5000,
		NotLoadCacheAtStart: true,
		LogDir:              "/tmp/nacos/log",
		CacheDir:            "/tmp/nacos/cache",
		LogLevel:            "debug"}
	serverConfigs := []constant.ServerConfig{
		{
			IpAddr:      nas.Host,
			ContextPath: "/nacos",
			Port:        uint64(nas.Port),
			Scheme:      "http"}}
	client, _ := clients.CreateConfigClient(map[string]interface{}{
		"serverConfigs": serverConfigs,
		"clientConfig":  clientConfig})
	content, _ := client.GetConfig(vo.ConfigParam{
		DataId: nas.Data,
		Group:  nas.Group})

	err = json.Unmarshal([]byte(content), &config.Nas)
	if err != nil {
		fmt.Println("nacos连接失败")
		return
	}
	fmt.Println("nacos初始化成功")
	err = client.ListenConfig(vo.ConfigParam{
		DataId: nas.Data,
		Group:  nas.Group,
		OnChange: func(namespace, group, dataId, data string) {
			fmt.Println("group:" + group + ", dataId:" + dataId + ", data:" + data)
		},
	})

}
